/**
 * Project Name:HomeActivity
 * Date:2016-1-22下午3:41:45
 * Copyright (c) 2016, askzhao All Rights Reserved.
 *
 */
package com.kkd.kkdapp.view.EditText;

import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.regex.PatternSyntaxException;

import android.content.Context;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.widget.EditText;

/**
 * 金融类资金输入框
 * @author askzhao
 * @version
 */
public class FinanceEditText extends EditText {

	private boolean isOnlyInteger = false;// 控制 输入框是否只能输入整数 ，为false时可以输入带2位小数的实数
	private double mLimitMax = -1; // 输入最大限额 -1表示不限制
	private int mDecimalDigits = 2;// 输入框小数的位数,默认为2位
	private onFinanceEditListener mFinanceEditListener;
	private double toValue = 0;
	private double fromValue = 0;
	private Context mContext;
	private TextWatcher mTextWatcher = new TextWatcher() {

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {

			if (isOnlyInteger || mDecimalDigits == 0) {
				// 只能输入整数
				inputCheckoutOnlyInteger();
			} else {
				inputCheckout();

			}
			toValue = overLimitCheck();
			if(mFinanceEditListener!=null){
				if(toValue!=fromValue)
					mFinanceEditListener.onValueChanged( toValue, fromValue);
			}
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
		}

		@Override
		public void afterTextChanged(Editable s) {
			if(mFinanceEditListener!=null&&toValue!=fromValue){
				fromValue = toValue;
				mFinanceEditListener.afterValueChanged(fromValue);
			}
		}
	};

	public FinanceEditText(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		mContext = context;
		init();
	}

	public FinanceEditText(Context context, AttributeSet attrs) {
		super(context, attrs);
		mContext = context;
		init();
	}

	public FinanceEditText(Context context) {
		super(context);
		mContext = context;
		init();
	}

	/**
	 * init:(这里用一句话描述这个方法的作用). <br/>
	 * 
	 * @author askzhao
	 */
	private void init() {
		setLongClickable(false);
		setTextIsSelectable(false);
		addTextChangedListener(mTextWatcher);
	}


	public void setOnlyInteger(boolean isOnlyInteger) {
		this.isOnlyInteger = isOnlyInteger;
		mDecimalDigits = 0;
	}

	public void setLimitMax(double nLimitMax) {
		mLimitMax = nLimitMax;
	}

	public void setDecimalDigits(int decimalDigits) {
		mDecimalDigits = decimalDigits;
	}

	/**
	 * 提现金额输入 合法性校验,带小数的校验
	 */
	protected void inputCheckout() {
		String inputmoney = getText().toString();
		if (".".equals(inputmoney.toString())) { // 输入提现金额首位为“.”
			setText("");
			setSelection(getText().toString().length());
			return;
		}
		String dValue = inputmoney.toString();
		String[] splitArray = dValue.split("\\.");
		String newValue;

		if (decimals(inputmoney)) { // 输入金额为整数、两位小数

			// 去掉合法输入的首位的0
			boolean isReset = false;
			while (splitArray[0].startsWith("0") && splitArray[0].length() > 1) {
				splitArray[0] = splitArray[0].substring(1);
				isReset = true;
			}
			if (splitArray.length > 1) {
				newValue = splitArray[0] + "." + splitArray[1];
			} else {
				newValue = splitArray[0];
			}
			if (isReset) {
				setText(newValue);
				setSelection(getText().toString().length());
			}

		} else { // 输入金额不为整数、两位小数

			if (TextUtils.isEmpty(splitArray[0])) {
				splitArray[0] = "0";
			} else {
				// 去掉合法输入的首位的0
				double first2 = Double.parseDouble(splitArray[0]);
				splitArray[0] = String.valueOf(((int) first2));
			}
			if (splitArray.length > 1) {
				newValue = splitArray[0] + "." + splitArray[1];
			} else {
				newValue = splitArray[0] + ".";
			}

			String[] splitArray2 = newValue.split("\\.");
			if (splitArray2.length > 1) {
				String dotValue = splitArray2[1];
				int diff = dotValue.length() - mDecimalDigits;
				if (diff < 0)
					diff = 0;
				newValue = newValue.substring(0, splitArray2[0].length()
						+ splitArray2[1].length() + 1 - diff);
			}
			setText(newValue);
			setSelection(getText().toString().length());
		}

	}

	/******
	 * 
	 * 校验合法性。输入职位整数时
	 ********/
	protected void inputCheckoutOnlyInteger() {
		String inputmoney = getText().toString();
		if (inputmoney.contains(".")) { // 去掉整数情况下末尾的小数点
			setText(inputmoney.replace(".", ""));
			setSelection(getText().toString().length());
		}
		if (decimals(inputmoney)) { // 输入金额为整数、两位小数

			// 去掉合法输入的首位的0
			boolean isReset = false;
			while (inputmoney.startsWith("0") && inputmoney.length() > 1) {
				inputmoney = inputmoney.substring(1);
				isReset = true;
			}

			if (isReset) {// 文本需要修改，因为要去掉0
				setText(inputmoney);
				setSelection(getText().toString().length());
			}

		} else { // 输入金额不为整数、两位小数
		}

	}

	/**
	 * 提现金额超限后的处理逻辑
	 */
	public double overLimitCheck() {
		double want = 0;
		try {
			want = Double.parseDouble(getText().toString());
		} catch (Exception e) {
			// 忽略
		}
		if (mLimitMax >= 0 && want > mLimitMax) {
			if(mFinanceEditListener!=null){
				 mFinanceEditListener.onOutLimit();
			}
			if (isOnlyInteger || mDecimalDigits == 0) {// 格式化为整数
				setText(String.valueOf((int) mLimitMax));
				setSelection(getText().toString().length());
			} else {// 格式化为对应小数位数的实数
				String format = "0.";
				for (int i = 0; i < mDecimalDigits; i++) {
					format = format + "0";
				}
				DecimalFormat df = new DecimalFormat(format);
				// 采取舍位处理，不然会死循环
				df.setRoundingMode(RoundingMode.DOWN);
				setText(df.format(mLimitMax));
				setSelection(getText().toString().length());
			}
			try {
				want = Double.parseDouble(getText().toString());
			} catch (Exception e) {
				// 忽略
			}
		}
		
		return want;
	}

	// 数字格式是否正确
	public boolean decimals(String str) throws PatternSyntaxException {

		String regex = "^?\\d*([.]\\d{0," + mDecimalDigits + "})?$";
		if (isOnlyInteger || mDecimalDigits == 0) {
			regex = "^\\+?[0-9][0-9]*$";
		}

		return str.matches(regex);
	}

	public void setFinanceEditListener(onFinanceEditListener listener) {
		mFinanceEditListener = listener;
	}

	public interface onFinanceEditListener {

		public void onValueChanged(double toValue, double fromValue);

		public void afterValueChanged(double toValue);

		public void onOutLimit();

	}


}
